# api/teacher.py
from flask import Blueprint, request, jsonify
from models import db, Teacher, Title, College, TeachingRecord,Course
from sqlalchemy import func


teachers_bp = Blueprint('teachers', __name__)

# 获取教师列表，支持根据学院筛选
@teachers_bp.route('/api/teachers', methods=['GET'])
def get_teachers():
    college_id = request.args.get('college_id')  # 获取学院ID，如果没有传递则返回所有教师

    query = Teacher.query

    # 如果传入了学院ID，则进行筛选
    if college_id:
        query = query.filter_by(college_id=college_id)

    # 查询所有教师数据
    teachers = query.all()

    result = []
    for teacher in teachers:
        # 计算教师当前学期授课学时
        teaching_records = TeachingRecord.query.filter_by(teacher_id=teacher.teacher_id, is_teaching=True).all()
        total_teaching_hours = sum([tr.teaching_count for tr in teaching_records])

        # 获取职称和学院信息
        title = Title.query.get(teacher.title_id)
        college = College.query.get(teacher.college_id)

        # 计算剩余可授课学时
        max_teaching_hours = title.teaching_limit if title else 0

        total_teaching_hours = db.session.query(func.sum(Course.course_hours)) \
                             .join(TeachingRecord, TeachingRecord.course_id == Course.course_id) \
                             .filter(TeachingRecord.teacher_id == teacher.teacher_id,
                                     TeachingRecord.is_teaching == True) \
                             .scalar() or 0

        available_hours = max_teaching_hours - total_teaching_hours

        # 将教师信息添加到结果列表
        result.append({
            'teacher_id': teacher.teacher_id,
            'name': teacher.name,
            'title_name': title.title_name if title else 'N/A',  # 职称名称
            'college_name': college.college_name if college else 'N/A',  # 学院名称
            'teaching_count': total_teaching_hours,  # 总授课学时
            'available_hours': available_hours  # 剩余可授课学时
        })

    return jsonify(result)

# 获取所有职称
@teachers_bp.route('/api/titles', methods=['GET'])
def get_titles():
    titles = Title.query.all()
    result = [{'title_id': title.title_id, 'title_name': title.title_name} for title in titles]
    return jsonify(result)

# 获取所有学院
@teachers_bp.route('/api/colleges', methods=['GET'])
def get_colleges():
    colleges = College.query.all()
    result = [{'college_id': college.college_id, 'college_name': college.college_name} for college in colleges]
    return jsonify(result)

# 添加教师
@teachers_bp.route('/api/teachers', methods=['POST'])
def add_teacher():
    data = request.get_json()

    if not data or 'name' not in data or 'title_id' not in data or 'college_id' not in data:
        return jsonify({'message': 'Missing required fields'}), 400

    new_teacher = Teacher(
        name=data['name'],
        title_id=data['title_id'],
        college_id=data['college_id']
    )
    db.session.add(new_teacher)
    db.session.commit()

    return jsonify({
        'teacher_id': new_teacher.teacher_id,
        'name': new_teacher.name,
        'title_id': new_teacher.title_id,
        'college_id': new_teacher.college_id
    }), 201

# 更新教师
@teachers_bp.route('/api/teachers/<int:teacher_id>', methods=['PUT'])
def update_teacher(teacher_id):
    data = request.get_json()
    teacher = Teacher.query.get(teacher_id)

    if not teacher:
        return jsonify({'message': 'Teacher not found'}), 404

    teacher.name = data['name']
    teacher.title_id = data['title_id']
    teacher.college_id = data['college_id']
    db.session.commit()

    return jsonify({'message': 'Teacher updated successfully'})


# 获取教师授课记录
@teachers_bp.route('/api/teachers/<int:teacher_id>/records', methods=['GET'])
def get_teacher_records(teacher_id):
    # 获取教师的教学记录
    records = TeachingRecord.query.filter_by(teacher_id=teacher_id).all()
    result = []

    # 遍历每条记录
    for record in records:
        # 获取相关的课程信息
        course = Course.query.get(record.course_id)

        if course:
            record_data = {
                'course_name': course.course_name,
                'course_hours': course.course_hours,
                'is_teaching': record.is_teaching,
                'teaching_count': record.teaching_count
            }
            result.append(record_data)

    # 如果没有返回空列表
    return jsonify(result)